package org.jetnuke.common;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.velocity.VelocityContext;

public class ValidationSet {
	ArrayList list = new ArrayList();

	void addValidationItem(ValidationItem vi) {
		list.add(vi);
	}

	/**
	 * @param request
	 * @param vc
	 */
	public List validate(HttpServletRequest request, VelocityContext vc) {
		ArrayList errorsList = new ArrayList();
		for (int i = 0; i < list.size(); i++) {
			ValidationItem vi = (ValidationItem) list.get(i);
			String val = request.getParameter(vi.paramName);
			if (vi.required) {

				if (val == null || val.length() == 0) {
					errorsList.add(new ValidationError(vi.paramName,
							ValidationError.REQUIRED, vi.label, vc));
					continue;
				}
			}

			if (vi.getMinLength() != null) {
				if (val == null || val.length() < vi.getMinLength().intValue()) {
					errorsList.add(new ValidationError(vi.paramName,
							ValidationError.MINLENGTH, vi.label, vc));
					continue;
				}
			}
			if (vi.getMaxLength() != null) {
				if (val == null || val.length() > vi.getMaxLength().intValue()) {
					errorsList.add(new ValidationError(vi.paramName,
							ValidationError.MAXLENGTH, vi.label, vc));
					continue;
				}
			}
			if (vi.validationClass != null) {

				try {
					IValidate validate = (IValidate) Class.forName(
							vi.validationClass).newInstance();
					if (!validate.isValid(val)) {
						errorsList.add(new ValidationError(vi.paramName,
								ValidationError.NOT_VALID, vi.label, vc));
					}
				} catch (Exception e) {

					//Validation class not found or not valid!
				}
			}
		}
		return errorsList;

	}
}
